package com.health.common.config;

//import cn.dev33.satoken.context.SaHolder;
//import cn.dev33.satoken.interceptor.SaInterceptor;
//import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * 全局跨域配置
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@Configuration
@SuppressWarnings("deprecation")
@SpringBootConfiguration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 覆盖所有请求
        registry.addMapping("/**")
                // 允许发送 Cookie
                .allowCredentials(true)
                // 放行哪些域名（必须用 patterns，否则 * 会和 allowCredentials 冲突）
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .exposedHeaders("*");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        System.out.println("--------- flag 1");
        registry.addInterceptor(new SaInterceptor(handle -> {
                    System.out.println("--------- flag 2，请求进入了拦截器，访问的 path 是：" + SaHolder.getRequest().getRequestPath());
//                    StpUtil.checkLogin();  // 登录校验，只有会话登录后才能通过这句代码
                }))
                .addPathPatterns("/**")
                .excludePathPatterns("/auth/login","/users/info","/favicon.ico",
                        "/v3/api-docs/**","/webjars/**","/swagger**","/**/doc.html","/users/roleList","/**/create**","/users/**Register");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //静态资源：
        //    前端网站，访问 路径/web/** ，会在 项目resources/static/web/ 目录下查找
        //    文件，访问 路径/public/file/** ，会在 项目resources/static/public/file/ 目录下查找
        //    放图片，访问 路径/public/** 下的静态资源，会在 项目resources/static/public/image/ 目录下查找
        //swaggerUI：
        //    swagger第三方UI - Knife4j，访问地址为：http://localhost:8181/malldemo/doc.html
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }


}
